package cn.fancy.sdk.pay.weixin;

import android.widget.Toast;
import java.io.File;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import cn.fancy.sdk.FileUtils;
import cn.fancy.sdk.baseview.DialogView;
import cn.fancy.sdk.common.utils.ResUtil;

public class WXPayWebActivity extends Activity implements OnClickListener {
    
    private final static String URL = "url";
    private ValueCallback<Uri> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 1;
    
    private Button backIv;
	private WebView webView;
	private String url;
    private Dialog dialog;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(ResUtil.getLayoutId(WXPayWebActivity.this, "guild_newweb_pay_activity"));
        
        backIv = (Button) this.findViewById(ResUtil.getId(WXPayWebActivity.this, "guild_newpay_back"));
        backIv.setOnClickListener(this);
        
        webView = (WebView) this.findViewById(ResUtil.getId(WXPayWebActivity.this, "guild_new_pay_wv"));
        
        Intent intent = this.getIntent();
        url = intent.getStringExtra(URL);
        initView();
    
        dialog = DialogView.showWaitingDialog(WXPayWebActivity.this, new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                WXPayWebActivity.this.finish();
            }
        });
    }
    
    
    public void initView() {
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setAppCacheEnabled(false);
        webView.getSettings().setDatabaseEnabled(false);
        webView.getSettings().setDomStorageEnabled(false);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.loadUrl(url);
        
        webView.addJavascriptInterface(new JSInterface(), "JSInterface");
        webView.setWebViewClient(new WebViewClient() {
            
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 如下方案可在非微信内部WebView的H5页面中调出微信支付
                Log.e("shouldOverrideUrlLoad==", url);
                if (url.startsWith("weixin://")) {
                    
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
    
                    try {
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
    
                        // 读取微信是否安装的方法失效，使用此方法
                        Toast.makeText(WXPayWebActivity.this,
                            "您的手机没有安装微信，请安装后进行支付", Toast.LENGTH_LONG).show();
                        WXPayWebActivity.this.finish();
                    }
                    
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
            
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
            
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                DialogView.cancelDialog(dialog);
                webView.loadUrl("javascript:function finishActivity(){JSInterface.finishActivity();}");
            }
        });
        
        webView.setWebChromeClient(new WebChromeClient() {
            
            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                Log.i("UPFILE", "in openFile Uri Callback");
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                }
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }
            
            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                Log.i("UPFILE", "in openFile Uri Callback has accept Type" + acceptType);
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                }
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
                i.setType(type);
                startActivityForResult(Intent.createChooser(i, "File Chooser"),
                    FILECHOOSER_RESULTCODE);
            }
            
            // For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.i("UPFILE", "in openFile Uri Callback has accept Type" + acceptType + "has capture" + capture);
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                }
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
                i.setType(type);
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }
            //Android 5.0+
            
        });
    }
    
    
    public class JSInterface {
        @android.webkit.JavascriptInterface//4.0之后要加这个注解
        public void finish() {
            WXPayWebActivity.this.finish();
        }
    
        @android.webkit.JavascriptInterface
        public void finishActivity(){
            WXPayWebActivity.this.finish();
        }
    }
    
    @Override
    public void onBackPressed() {
        this.finish();
    }
    
    public static void start(Context context, String url) {
        Intent intent = new Intent();
        intent.putExtra(URL, url);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(context, WXPayWebActivity.class);
        context.startActivity(intent);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
			if (null == mUploadMessage) {
				return;
			}
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (result == null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
                return;
            }
            Log.i("UPFILE", "onActivityResult" + result.toString());
            String path = FileUtils.getPath(this, result);
            if (TextUtils.isEmpty(path)) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
                return;
            }
            Uri uri = Uri.fromFile(new File(path));
            Log.i("UPFILE", "onActivityResult after parser uri:" + uri.toString());
            mUploadMessage.onReceiveValue(uri);
            mUploadMessage = null;
        }
    }
    
    @Override
    public void onClick(View v) {
        if (v.getId() == ResUtil.getId(WXPayWebActivity.this, "guild_newpay_back")) {
            this.onBackPressed();
        }
    }
    
}
